package com.chance.cc.crawler.development.scripts.southmoney;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.interaction;

public class SouthMoneyCrawlerScript extends CrawlerCommonScript {
    private Logger log= LoggerFactory.getLogger(SouthMoneyCrawlerScript.class);


    @Override
    public String domain() {
        return "southmoney";
    }

    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    @Override
    public void initUrlRegulars() {
        addUrlRegular("http://www.southmoney.com/");
        addUrlRegular("http://www.southmoney.com/\\S*/");
        addUrlRegular("http://www.southmoney.com/\\S*/\\S*");
        addUrlRegular("http://www.southmoney.com/caijing/\\S*/\\d*/\\d*.html");
        addUrlRegular("http://www.southmoney.com/\\S*/\\d*/\\d*.html");
    }

    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks=new ArrayList<>();
        String requestUrl=httpPage.getRequest().getUrl();
        if(requestUrl.matches("http://www.southmoney.com/")){
            List<String> pageList=httpPage.getHtml().xpath("//li[@class=\"first\"]/dl/dd/a/@href").all();
            for (String listUrl:pageList){
                CrawlerRequestRecord turnPage = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(listUrl)
                            .httpUrl(listUrl)
                            .releaseTime(System.currentTimeMillis())
                            .build();
                    parsedLinks.add(turnPage);
            }

        }else if(requestUrl.matches("http://www.southmoney.com/\\S*/|http://www.southmoney.com/\\S*/\\S*")){
            List<Selectable> nodes=httpPage.getHtml().xpath("//ul[@class=\"newslist\"]/li").nodes();
            for (Selectable node:nodes){
                String itemUrl=node.xpath("./a/@href").get();

                if (StringUtils.isBlank(itemUrl)){
                    continue;
                }
                itemUrl="http://www.southmoney.com"+itemUrl;

                String pubTime = node.xpath("./span[@class=\"date\"]").get();
                if (StringUtils.isBlank(pubTime)){
                    continue;
                }
                try {
                    long releaseTime = DateUtils.parseDate(pubTime, "yyyy/MM/dd").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTime)
                            .resultLabelTag(article)
                            .needParsed(false)
                            .build();

                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
        }
        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRequestRecord, httpPage));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRequestRecord, httpPage));
        }
        // todo
        return crawlerDataList;
    }

    /**
     * 清洗文章
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        httpPage.getRequest().getUrl();
        try {

            List<String> texts = httpPage.getHtml().xpath("//div[@class=\"articleCon\"]/p/text()").all();
            String releaseTimeStr = httpPage.getHtml().xpath("//p[@class=\"artDate\"]").get();

            Matcher mtPubTime = Pattern.compile("\\d*[-/]\\d*[-/]\\d* \\d*[:]\\d*").matcher(releaseTimeStr);
            String pubTime = null;
            while (mtPubTime.find()){
                pubTime = mtPubTime.group(0);
            }

            String author=releaseTimeStr.substring(17).trim();

            StringBuffer conents = new StringBuffer();
            for (String text : texts) {
                conents.append(text).append(" ");
            }

            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1).split("\\.")[0];

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .url(itemUrl)
                    .releaseTime(DateUtils.parseDate(pubTime,"yyyy-MM-dd HH:mm").getTime())
                    .addContentKV("content",conents.toString().trim())
                    .addContentKV("title",httpPage.getHtml().xpath("//h1[@class=\"artTitle\"]/text()").get())
                    .addContentKV("author",author)
                    .build();
            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage(),e);
        }
        return null;

    }

    public CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        return null;
    }

    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }
}
